package com.woniuxy.util;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class MyUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {

        //告诉客户端浏览器返回数据类型格式，并告知编码规则（客户端将会以相同编码规则解析，则不会出现客户端中文乱码）
        //response.setCharacterEncoding("UTF-8");该设置只是将客户端响应编码格式设置utf-8
        response.setContentType("application/json;charset=utf-8");

        ResultVO resultVO = null;
        //BlockException  异常接口,包含Sentinel的五个异常
        //  FlowException  限流异常
        //  DegradeException  降级异常
        //  ParamFlowException  参数限流异常
        //  AuthorityException  授权异常
        //  SystemBlockException  系统负载异常
        if (e instanceof FlowException) {
            resultVO = new ResultVO(-1, "接口被限流了");
            log.error("接口被限流了");
        } else if (e instanceof DegradeException) {
            resultVO = new ResultVO(-2, "接口被降级了");
            log.error("接口被降级了");
        } else if (e instanceof AuthorityException) {
            resultVO = new ResultVO(-3, "接口未被授权");
            log.error("接口未被授权");
        } else if (e instanceof ParamFlowException) {
            resultVO = new ResultVO(-4, "参数被限流了");
            log.error("参数被限流了");
        }else if (e instanceof SystemBlockException) {
            resultVO = new ResultVO(-5, "被系统保护了");
            log.error("被系统保护了");
        }else{
            resultVO = new ResultVO(-6, "其他未知异常");
            log.error("其他未知异常");
        }
        response.getWriter().write(JSON.toJSONString(resultVO));
    }
}
